package com.example.springboot_manage.controller;

import com.alibaba.druid.util.StringUtils;
import com.example.springboot_manage.result.BaseResult;
import com.example.springboot_manage.util.ResultUtil;
import com.example.springboot_manage.util.FileResult;
import com.example.springboot_manage.pojo.Brand;
import com.example.springboot_manage.pojo.Goods;
import com.example.springboot_manage.pojo.GoodsCategory;
import com.example.springboot_manage.pojo.GoodsImages;
import com.example.springboot_manage.service.*;
import com.example.springboot_manage.vo.ResultVO;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


/**
 * 商品
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsCategoryService goodsCategoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsImagesService goodsImagesService;

    @Autowired
    private UploadService uploadService;

    private Logger logger;
    /**
     * 商品分类的添加跳转
     * @return
     */
    @RequestMapping("/category/add")
    public String categoryAdd(Model model){
        List<GoodsCategory> list = goodsCategoryService.selectCategoryTopList();
        model.addAttribute("gcList",list);
        return "goods/category/category-add";
    }

    /**
     * 商品分类列表跳转
     * @return
     */
    @RequestMapping("/category/list")
    public String categoryList(Model model){
        model.addAttribute("gcvList",goodsCategoryService.selectCategoryForView());
        return "goods/category/category-list";
    }

    /**
     * 父级显示子级的分类
     * @param parentId
     * @return
     */
    @RequestMapping("category/{parentId}")
    @ResponseBody
    public List<GoodsCategory> selectCategoryList(@PathVariable Short parentId){
        return goodsCategoryService.selectCategoryList(parentId);
    }

    /**
     * 保存分类
     * @param goodsCategory
     * @return
     */
    @RequestMapping("category/save")
    @ResponseBody
    public BaseResult saveCategory(GoodsCategory goodsCategory){
        int result = goodsCategoryService.categorySave(goodsCategory);
        return result>0? BaseResult.success():BaseResult.error();
    }

    /**
     * 商品列表跳转
     * @return
     */
    @RequestMapping("/list")
    public String goodsList(Model model){
        model.addAttribute("gcList",goodsCategoryService.selectCategoryList());
        model.addAttribute("brands",brandService.selectBrandList());
        return "goods/goods-list";
    }

    /**
     * 商品添加跳转
     * @return
     */
    @RequestMapping("/add")
    public String goodsAdd(Model model){
        List<GoodsCategory> gcList = goodsCategoryService.selectCategoryTopList();
        model.addAttribute("gcList",gcList);
        List<Brand> brands = brandService.selectBrandList();
        model.addAttribute("brands",brands);
        return "goods/goods-add";
    }

    @RequestMapping("/save")
    @ResponseBody
    public BaseResult goodsSave(Goods goods){
        return goodsService.saveGoods(goods);
    }

    /**
     * 商品-新增-相册保存（多张图片其实是多次调用该方法）
     *
     * @param file
     * @param goodsId
     * @return
     */
    @RequestMapping("images/save")
    @ResponseBody
    public BaseResult goodsImagesSave(MultipartFile file, Integer goodsId) {
        try {
            //获取文件名并重命名，防止文件名一样导致覆盖
            String filename = file.getOriginalFilename();
            //加上日期在上传时会根据日期创建目录
            String date = DateTimeFormatter.ofPattern("yyyy/MM/dd/").format(LocalDateTime.now());
            filename = date + System.currentTimeMillis() +
                    filename.substring(filename.lastIndexOf("."));
            FileResult fileResult = uploadService.upload(file.getInputStream(), filename);
            //判断图片是否上传成功
            if (!StringUtils.isEmpty(fileResult.getFileUrl())) {
                GoodsImages goodsImages = new GoodsImages();
                goodsImages.setGoodsId(goodsId);
                goodsImages.setImageUrl(fileResult.getFileUrl());
                return goodsImagesService.saveGoodsImages(goodsImages);
            }
        } catch (IOException e) {
            logger.error("文件上传错误，失败原因：" + e.getMessage());
        }
        return BaseResult.error();
    }

    /**
     * 商品-列表-分页查询
     * @param goods
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("listForPage")
    @ResponseBody
    public BaseResult selectGoodsListByPage(Goods goods,Integer pageNum,Integer pageSize){
        return goodsService.selectGoodsListByPage(goods,pageNum,pageSize);
    }






}
